package sp.servlet;

import com.alibaba.fastjson.JSON;
import sp.dao.Page;
import sp.dao.UserDao;
import sp.dao.UserDaoImpl;
import sp.entity.Novel;
import sp.entity.User;
import sp.service.UserService;
import sp.service.UserServiceImpl;
import sp.util.ParamUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        String userName = req.getParameter("userName");
        String userId = req.getParameter("userId");
        int page = ParamUtil.parseInt(req.getParameter("page"),0);
        int rows = ParamUtil.parseInt(req.getParameter("rows"),0);
        Page<User> pageBean = userService.findByPage(userId,userName,page,rows);
        List<User> usersList = userService.findAll();
        Map map = new HashMap();
        map.put("data",pageBean);
        map.put("userList",usersList);
        resp.getWriter().write(JSON.toJSONString(map));
        resp.getWriter().flush();
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        String id = req.getParameter("id");
        String resultFormat = "{\"state\":\"%b\",\"error\":\"%s\"}";
        String result = "";
        try {
            userService.delete(id);
            result = String.format(resultFormat,true,"");
        } catch (RuntimeException e){
            result  = String.format(resultFormat,false,e.getMessage());
        }
        resp.getWriter().write(result);
        resp.flushBuffer();
    }
}
